(function(){
  'use strict';

  if (!window.Api || !window.UI) return;

  var marketList = document.getElementById('market-list');
  if (!marketList) return;

  var state = { page: 1, pageSize: 8, q: '', market_type: '', status: '', order: 'desc' };
  var itemsAll = []; var subsById = new Set(); var subsByCode = new Set();
  var filterBar=null; var pager=null;

  function statusText(x){ if (x.status) return x.status; if (typeof x.active==='boolean') return x.active?'active':'paused'; return ''; }

  function ensureFilter(){ if (filterBar) return; filterBar=document.createElement('div'); filterBar.style.display='flex'; filterBar.style.gap='8px'; filterBar.style.margin='8px 0';
    function make(ph,key,type){ var el=document.createElement(type==='select'?'select':'input'); el.className='input'; if(type!=='select') el.placeholder=ph; if(type==='select'){ var o0=document.createElement('option'); o0.value=''; o0.textContent=ph; el.appendChild(o0);} el.setAttribute('data-key',key); el.addEventListener('input',on); el.addEventListener('change',on); return el; }
    function on(){ var k=this.getAttribute('data-key'); var v=(this.value||'').trim(); state[k]=v; state.page=1; render(); }
    var q=make('搜索名称/符号','q'); var mk=make('市场类型','market_type','select'); var o1=document.createElement('option'); o1.value='spot'; o1.textContent='spot'; mk.appendChild(o1); var o2=document.createElement('option'); o2.value='perpetual'; o2.textContent='perpetual'; mk.appendChild(o2);
    var st=make('状态','status','select'); ['active','paused'].forEach(function(v){ var o=document.createElement('option'); o.value=v; o.textContent=v; st.appendChild(o); });
    var od=document.createElement('select'); od.className='input'; var d0=document.createElement('option'); d0.value='desc'; d0.textContent='创建时间：降序'; var d1=document.createElement('option'); d1.value='asc'; d1.textContent='创建时间：升序'; od.appendChild(d0); od.appendChild(d1); od.value=state.order; od.addEventListener('change', function(){ state.order=this.value; render(); });
    var container = marketList.parentNode; filterBar.appendChild(q); filterBar.appendChild(mk); filterBar.appendChild(st); filterBar.appendChild(od); container.insertBefore(filterBar, marketList);
  }

  function render(){
    var arr = itemsAll.slice();
    if (state.q){ var qlc=state.q.toLowerCase(); arr=arr.filter(function(x){ return String(x.name||x.code||'').toLowerCase().indexOf(qlc)>=0 || String(x.symbol||'').toLowerCase().indexOf(qlc)>=0; }); }
    if (state.market_type) arr = arr.filter(function(x){ return (x.market_type||'')===state.market_type; });
    if (state.status) arr = arr.filter(function(x){ return statusText(x)===state.status; });
    arr.sort(function(a,b){ var ta=Date.parse(a.created_at||'')||0; var tb=Date.parse(b.created_at||'')||0; return state.order==='asc' ? (ta-tb) : (tb-ta); });

    var total = arr.length; var start=(state.page-1)*state.pageSize; var pageItems = arr.slice(start, start+state.pageSize);
    marketList.innerHTML='';
    if (!pageItems.length){ marketList.innerHTML='<li class="muted">无匹配策略</li>'; updatePager(total); return; }
    for (var i=0;i<pageItems.length;i++){
      (function(s){
        var li=document.createElement('li');
        var btn=document.createElement('button'); btn.className='btn';
        var isSub=(s && ((s.id && subsById.has(s.id)) || (s.code && subsByCode.has(s.code))));
        btn.textContent=isSub?'已订阅':'订阅'; btn.disabled=!!isSub; if(!isSub) btn.addEventListener('click', function(){ if (window.openSubscribeModal) window.openSubscribeModal(s); });
        var left=document.createElement('div'); var title=document.createElement('div'); title.textContent=(s.name||s.code||'策略');
        var status=statusText(s); var badge=document.createElement('span'); badge.textContent=status||''; badge.style.marginLeft='6px'; badge.style.fontSize='12px'; badge.style.padding='2px 6px'; badge.style.borderRadius='10px'; badge.style.color=status==='active'?'#0a7a30':'#6b7280'; badge.style.background=status==='active'?'#dcfce7':'#f3f4f6'; title.appendChild(badge);
        var meta=document.createElement('div'); meta.className='small muted'; var parts=[]; if(s.symbol) parts.push('符号: '+s.symbol); if(s.market_type) parts.push('市场: '+s.market_type); if(status) parts.push('状态: '+status); if(s.created_at) parts.push('创建: '+s.created_at); meta.textContent=parts.join(' · ');
        left.appendChild(title); left.appendChild(meta);
        li.style.display='flex'; li.style.justifyContent='space-between'; li.style.alignItems='center';
        li.appendChild(left); li.appendChild(btn); marketList.appendChild(li);
      })(pageItems[i]);
    }
    updatePager(total);
  }

  function updatePager(total){
    var container=marketList.parentNode; if(!pager){ pager=document.createElement('div'); pager.style.display='flex'; pager.style.justifyContent='space-between'; pager.style.alignItems='center'; pager.style.marginTop='8px'; container.appendChild(pager); }
    pager.innerHTML=''; var page=state.page; var size=state.pageSize; var max=Math.max(1, Math.ceil((total||0)/size));
    var info=document.createElement('span'); info.className='muted small'; info.textContent='第 '+page+' / '+max+' 页 · 共 '+total+' 条';
    var ctr=document.createElement('div'); ctr.style.display='flex'; ctr.style.gap='8px'; var prev=document.createElement('button'); prev.className='btn'; prev.textContent='上一页'; prev.disabled=page<=1; prev.addEventListener('click', function(){ state.page=Math.max(1,state.page-1); render(); }); var next=document.createElement('button'); next.className='btn'; next.textContent='下一页'; next.disabled=page>=max; next.addEventListener('click', function(){ state.page=Math.min(max,state.page+1); render(); }); ctr.appendChild(prev); ctr.appendChild(next); pager.appendChild(info); pager.appendChild(ctr);
  }

  async function load(){
    try{
      var pair = await Promise.all([
        Api.request('GET','/scripts/market',null,true).catch(function(){ return Api.request('GET','/scripts',null,true); }),
        Api.request('GET','/subscriptions',null,true)
      ]);
      var scripts = await Api.jsonOrThrow(pair[0]); var subs = []; try{ subs = await Api.jsonOrThrow(pair[1]); }catch(_){ subs=[]; }
      itemsAll = Array.isArray(scripts)?scripts:[]; subsById=new Set(); subsByCode=new Set(); if(Array.isArray(subs)){ for(var i=0;i<subs.length;i++){ var it=subs[i]||{}; if(it.enabled===false) continue; if(it.script_id!=null) subsById.add(it.script_id); if(it.script_code) subsByCode.add(it.script_code); }}
      ensureFilter(); render();
    }catch(_){ marketList.innerHTML='<li class="muted">加载失败</li>'; }
  }

  window.openSubscribeModal = window.openSubscribeModal || function(script){ if (window.app && typeof window.app.openSubscribeModal === 'function') window.app.openSubscribeModal(script); };
  load();
})();


